//
//  BTTbarBar.m
//  halfSweat
//
//  Created by 甘伟杰 on 16/5/12.
//  Copyright © 2016年 ganweijie. All rights reserved.
//

#import "BTTbarBar.h"
#import "BTButton.h"

#define kDefaultClick 1         // 调试时设置点击按钮

@interface BTTbarBar ()
/** 选中按钮 */
@property (weak, nonatomic) BTButton *selectedButton;
@end

@implementation BTTbarBar

-(void)setTabBarItems:(NSArray<UITabBarItem *> *)tabBarItems
{
    _tabBarItems = tabBarItems;
    
    NSInteger count = tabBarItems.count;
    
    CGFloat buttonX = 0;
    CGFloat buttonY = 0;
    CGFloat buttonH = self.frame.size.height;
    CGFloat buttonW = self.frame.size.width / count;
    
    for (NSInteger i = 0; i < count; i++) {
        BTButton *button = [[BTButton alloc] init];
        button.tag = i;
        buttonX = buttonW * i;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        [button setImage:tabBarItems[i].image forState:UIControlStateNormal];
        [button setImage:tabBarItems[i].selectedImage forState:UIControlStateSelected];
        [button setTitle:tabBarItems[i].title forState:UIControlStateNormal];
        
        [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
        if (i == 0) {   // 设置默认点击按钮
            [self buttonDidClick:button];
        }
    };
    
}

-(void)layoutSubviews{
    [super layoutSubviews];

    NSInteger count = self.tabBarItems.count;
    
    // 布局子控件
    CGFloat buttonX = 0;
    CGFloat buttonY = 0;
    CGFloat buttonW = self.bounds.size.width / 4;
    CGFloat buttonH = self.bounds.size.height;

    for (NSInteger i = 0; i < count; i++) {
        BTButton *button = [[BTButton alloc] init];
        buttonX = buttonW * i;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
    };
}

#pragma mark - 按钮点击事件
- (void)buttonDidClick:(BTButton *)button {
    
    // 设置选中按钮
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    if (_operationBlock) {  // 传值代理操作
        _operationBlock(button.tag);
    }
}

@end
